<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2 class="sidebar-title">在线教育平台</h2>
        <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
      </div>
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#0b1b33"
          text-color="#fff"
          active-text-color="#409EFF"
          :collapse="isSidebarCollapse"
          router
      >
        <el-menu-item index="/stuhome">
          <el-icon><menu /></el-icon>
          <span>全部课程</span>
        </el-menu-item>
        <el-menu-item index="/myclass">
          <el-icon><menu /></el-icon>
          <span>我的课程</span>
        </el-menu-item>
        <el-menu-item index="/question">
          <el-icon><folder /></el-icon>
          <span>提问</span>
        </el-menu-item>
        <el-menu-item index="/stuper">
          <el-icon><user /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item><router-link to="/myCourses">我的课程</router-link></el-breadcrumb-item>
        <el-breadcrumb-item>{{ courseName }}</el-breadcrumb-item>
        <el-breadcrumb-item>课程提问</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">课程提问</h1>
        <div class="course-info">
          <span class="course-name">{{ courseName }}</span>
          <span class="teacher">讲师：{{ teacher }}</span>
        </div>
      </div>

      <!-- 提问列表 -->
      <el-card class="question-list-card">
        <div class="question-list-header">
          <h3 class="header-title">已有提问</h3>
          <div class="header-actions">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索问题"
                clearable
                @keyup.enter.native="searchQuestions"
            >
              <template #append>
                <el-button @click="searchQuestions">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="showQuestionDialog">
              <i class="el-icon-plus"></i>提问
            </el-button>
          </div>
        </div>

        <!-- 问题列表 -->
        <div class="questions-container">
          <div v-for="(question, index) in filteredQuestions" :key="question.id" class="question-item">
            <div class="question-header">
              <div class="user-info">
                <img :src="question.avatar" alt="用户头像" class="avatar">
                <div class="user-details">
                  <div class="user-name">{{ question.userName }}</div>
                  <div class="question-time">{{ question.createTime }}</div>
                </div>
              </div>
              <div class="question-status" v-if="question.isAnswered">
                <el-tag type="success">已解答</el-tag>
              </div>
            </div>
            <div class="question-content">
              <h4 class="question-title">{{ question.title }}</h4>
              <p class="question-desc">{{ question.content }}</p>
            </div>
            <div class="question-actions">
              <span class="like-count">
                <i class="el-icon-thumbs-up"></i>{{ question.likeCount }}
              </span>
              <el-button
                  type="text"
                  size="small"
                  @click="toggleAnswerVisibility(index)"
              >
                {{ question.showAnswer ? '收起回答' : '查看回答' }}
              </el-button>
            </div>

            <!-- 回答内容 -->
            <div class="answer-container" v-if="question.showAnswer && question.isAnswered">
              <div class="answer-header">
                <div class="user-info">
                  <img src="https://picsum.photos/40/40?random=teacher" alt="讲师头像" class="avatar">
                  <div class="user-details">
                    <div class="user-name">{{ teacher }}</div>
                    <div class="answer-time">{{ question.answerTime }}</div>
                  </div>
                </div>
              </div>
              <div class="answer-content">
                <p>{{ question.answer }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredQuestions.length"
          />
        </div>

        <!-- 暂无数据提示 -->
        <div v-if="questions.length === 0" class="empty-question-list">
          <img src="https://picsum.photos/300/200?random=empty" alt="暂无提问" class="empty-image">
          <p class="empty-text">暂无提问，你可以发起第一个提问</p>
          <el-button
              type="primary"
              @click="showQuestionDialog"
          >
            发起提问
          </el-button>
        </div>
      </el-card>
    </div>
  </div>

  <!-- 提问对话框 -->
  <el-dialog :visible.sync="questionDialogVisible" title="发起提问">
    <el-form :model="newQuestion" ref="questionFormRef" label-width="100px">
      <el-form-item label="问题标题" prop="title">
        <el-input v-model="newQuestion.title" placeholder="请输入问题标题" />
      </el-form-item>
      <el-form-item label="问题内容" prop="content">
        <el-input
            v-model="newQuestion.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述你的问题..."
        />
      </el-form-item>
      <el-form-item label="问题分类" prop="category">
        <el-select v-model="newQuestion.category" placeholder="请选择问题分类">
          <el-option label="课程内容" value="content" />
          <el-option label="作业疑问" value="assignment" />
          <el-option label="考试相关" value="exam" />
          <el-option label="技术问题" value="technical" />
          <el-option label="其他问题" value="other" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="questionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQuestion">提交问题</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import {
  Menu,  // 保留需要的图标
  User,
  Search,
  Plus
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 侧边栏相关状态
const isSidebarCollapse = ref(false)
const activeMenu = ref('myCourses')
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value
}

// 课程信息
const courseId = ref(1)
const courseName = ref('Vue3 实战教程')
const teacher = ref('张教授')

// 问题列表相关状态
const state = reactive({
  questions: [], // 问题列表
  currentPage: 1, // 当前页码
  pageSize: 5, // 每页显示数量
  searchKeyword: '', // 搜索关键词
  questionDialogVisible: false, // 提问对话框是否显示
  newQuestion: {
    title: '',
    content: '',
    category: 'content'
  }
})

const {
  questions,
  currentPage,
  pageSize,
  searchKeyword,
  questionDialogVisible,
  newQuestion
} = state

// 表单引用
const questionFormRef = ref(null)

// 计算属性：根据关键词过滤问题
const filteredQuestions = computed(() => {
  if (!searchKeyword.trim()) {
    return questions
  }

  const keyword = searchKeyword.toLowerCase().trim()
  return questions.filter(question =>
      question.title.toLowerCase().includes(keyword) ||
      question.content.toLowerCase().includes(keyword) ||
      question.userName.toLowerCase().includes(keyword)
  )
})

// 模拟获取问题列表数据
const fetchQuestions = () => {
  // 这里模拟接口请求，实际开发中替换为真实的 API 调用
  setTimeout(() => {
    questions.splice(0, questions.length)
    // 模拟返回的数据
    const mockData = [
      {
        id: 1,
        title: "Vue3的Composition API和Options API有什么区别？",
        content: "我在学习Vue3的过程中，对Composition API和Options API的使用场景和优势不太清楚，能否请老师讲解一下？",
        category: "content",
        userName: "李同学",
        avatar: "https://picsum.photos/40/40?random=1",
        createTime: "2023-05-15 10:23",
        isAnswered: true,
        answer: "Vue3的Composition API是一个重大的新特性，它主要解决了Options API在处理复杂组件时导致的代码组织混乱问题...",
        answerTime: "2023-05-15 16:45",
        likeCount: 12,
        showAnswer: false
      },
      {
        id: 2,
        title: "关于课程示例代码的问题",
        content: "在第5章的示例代码中，我发现useFetch hook的实现方式和官方文档不太一样，请问这里有什么特殊考虑吗？",
        category: "content",
        userName: "王同学",
        avatar: "https://picsum.photos/40/40?random=2",
        createTime: "2023-05-14 09:15",
        isAnswered: true,
        answer: "这里主要是考虑到课程的教学目标，为了让大家更好地理解基本原理，所以采用了简化的实现方式...",
        answerTime: "2023-05-14 14:30",
        likeCount: 8,
        showAnswer: false
      },
      {
        id: 3,
        title: "作业提交截止时间是什么时候？",
        content: "请问第一章的作业提交截止时间是什么时候？是否可以延期提交？",
        category: "assignment",
        userName: "赵同学",
        avatar: "https://picsum.photos/40/40?random=3",
        createTime: "2023-05-13 15:40",
        isAnswered: true,
        answer: "第一章作业的截止时间是本周五（5月19日）23:59，原则上不接受延期提交，如有特殊情况请联系助教...",
        answerTime: "2023-05-13 17:05",
        likeCount: 5,
        showAnswer: false
      },
      {
        id: 4,
        title: "npm安装依赖失败",
        content: "在按照课程步骤安装依赖时，npm install命令总是报错，错误信息是...",
        category: "technical",
        userName: "陈同学",
        avatar: "https://picsum.photos/40/40?random=4",
        createTime: "2023-05-12 11:20",
        isAnswered: false,
        likeCount: 3,
        showAnswer: false
      },
      {
        id: 5,
        title: "关于考试形式的问题",
        content: "请问这门课程的期末考试是线上还是线下？考试形式是选择题还是编程题？",
        category: "exam",
        userName: "孙同学",
        avatar: "https://picsum.photos/40/40?random=5",
        createTime: "2023-05-10 08:30",
        isAnswered: true,
        answer: "本课程的期末考试将采用线上闭卷形式，考试内容包括选择题、简答题和编程题...",
        answerTime: "2023-05-10 11:15",
        likeCount: 10,
        showAnswer: false
      }
    ]

    questions.push(...mockData)
  }, 500)
}

onMounted(() => {
  fetchQuestions()
})

// 搜索问题
const searchQuestions = () => {
  currentPage.value = 1
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 显示提问对话框
const showQuestionDialog = () => {
  // 重置表单
  newQuestion.title = ''
  newQuestion.content = ''
  newQuestion.category = 'content'

  questionDialogVisible.value = true
  // 延迟聚焦到标题输入框
  setTimeout(() => {
    const titleInput = document.querySelector('.el-dialog input')
    if (titleInput) {
      titleInput.focus()
    }
  }, 300)
}

// 提交问题
const submitQuestion = () => {
  questionFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交问题
      setTimeout(() => {
        // 创建新问题对象
        const newId = questions.length > 0 ? Math.max(...questions.map(q => q.id)) + 1 : 1
        const now = new Date()
        const formattedTime = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`

        const newQuestionObj = {
          id: newId,
          title: newQuestion.title,
          content: newQuestion.content,
          category: newQuestion.category,
          userName: '我',
          avatar: 'https://picsum.photos/40/40?random=me',
          createTime: formattedTime,
          isAnswered: false,
          likeCount: 0,
          showAnswer: false
        }

        // 添加到问题列表开头
        questions.unshift(newQuestionObj)

        // 关闭对话框
        questionDialogVisible.value = false

        // 显示成功提示
        ElMessage.success('提问提交成功，等待讲师回复')
      }, 800)
    } else {
      ElMessage.error('请完善问题信息')
    }
  })
}

// 切换回答可见性
const toggleAnswerVisibility = (index) => {
  questions[index].showAnswer = !questions[index].showAnswer
}

// 监听侧边栏折叠状态
watch(isSidebarCollapse, (newVal) => {
  // 可在此处添加侧边栏折叠后的额外逻辑
})
</script>




<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse .main-content {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.course-info {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 16px;
}

.course-name {
  margin-right: 20px;
  font-weight: 500;
}

/* 提问列表卡片样式 */
.question-list-card {
  margin-bottom: 20px;
}

.question-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.header-actions .el-input {
  width: 300px;
  margin-right: 15px;
}

/* 问题列表样式 */
.questions-container {
  margin-bottom: 20px;
}

.question-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.question-item:last-child {
  border-bottom: none;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.question-time, .answer-time {
  font-size: 12px;
  color: #909399;
}

.question-status {
  margin-left: 10px;
}

.question-content {
  margin-bottom: 10px;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.question-desc {
  color: #606266;
  line-height: 1.5;
  margin-bottom: 0;
}

.question-actions {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.like-count {
  margin-right: 20px;
  cursor: pointer;
}

.like-count:hover {
  color: #409EFF;
}

.answer-container {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-header {
  margin-bottom: 10px;
}

.answer-content {
  color: #606266;
  line-height: 1.5;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 空问题列表样式 */
.empty-question-list {
  text-align: center;
  padding: 50px 0;
}

.empty-image {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  color: #909399;
  margin-bottom: 20px;
}
</style>

